package com.ms.config;

import com.ms.interceptor.AdminInterceptor;
import com.ms.interceptor.AdminOrOrganizerInterceptor;
import com.ms.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private TokenInterceptor tokenInterceptor;
    
    @Autowired
    private AdminInterceptor adminInterceptor;
    
    @Autowired
    private AdminOrOrganizerInterceptor adminOrOrganizerInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                // 排除举办方的登录注册接口
                .excludePathPatterns("/organizer/login")// 排除举办方登录接口
                .excludePathPatterns("/organizer/register")// 排除举办方注册接口
                .excludePathPatterns("/organizer/retrievePassword")
                // 排除普通用户注册和登录接口
                .excludePathPatterns("/api/user/register")// 排除用户注册接口
                // 排除静态资源路径（关键：添加 /place/**）
                .excludePathPatterns("/static/**", "/P_place/**") // 同时保留原 /static/** 防止其他情况
                .excludePathPatterns("/api/user/login");// 排除用户登录接口


        // 添加管理员权限拦截器
        registry.addInterceptor(adminInterceptor)
                .addPathPatterns("/manager/**") // 拦截所有管理员相关请求
                .excludePathPatterns("/manager/login"); // 排除管理员登录接口

        // 添加管理员或主办方权限拦截器
        registry.addInterceptor(adminOrOrganizerInterceptor)
                .addPathPatterns("/place/**"); // 拦截所有场地相关请求
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 对所有接口生效
                .allowedOriginPatterns("*") // 使用allowedOriginPatterns而不是allowedOrigins
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(false) // 设置为false避免冲突，或者明确指定allowedOriginPatterns
                .maxAge(3600); // 预检请求缓存时间
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保静态资源正确映射
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}